﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using TestAssemblyParser;
using System.Security.AccessControl;
using System.Security.Permissions;


namespace devtm.Applications
{

    [SecurityPermission(SecurityAction.Demand)]
    public class ApplicationStep
    {

        Assembly assembly;
        static ApplicationStep _instance;
        Guid Guid;
        Guid UserGuid;
        string Name;

        private string SubKey = string.Empty;

        #region Ctor
        
        static ApplicationStep()
        {
            _instance = new ApplicationStep();
        }

        public static ApplicationStep Instance { get { return _instance; } }

        private ApplicationStep()
        {

            // recupere l'id de l'appli
            assembly = Assembly.GetEntryAssembly();
            Name = assembly.GetName().Name;
            SubKey = @"SOFTWARE\devtm\Products\" + Name;

            GuidAttribute[] guids = (GuidAttribute[])assembly.GetCustomAttributes(typeof(GuidAttribute), false);
            foreach (GuidAttribute g in guids)
                Guid = new Guid(g.Value);

        }

        #endregion


        #region User

        public bool Initialize()
        {

            return true;

            UserGuid = new Guid(GetUserId() ?? CreateUserId());

            string license = ""; RegistryHelper.Read(Registry.CurrentUser, SubKey, "License").ToString();

            DateTime dte = GetDateEnd(license);
            if (dte < DateTime.Now)
            {

                ApplicationRegisterModelBack ret = Client.Register(new ApplicationRegisterModel() { GuidApplication = Guid.ToString(), GuidUser = UserGuid.ToString(), UserName = Environment.UserDomainName + @"\\" + Environment.UserName });
                if (ret.Result)
                {

                    //RegistryHelper.Write(Registry.CurrentUser, SubKey, "License", ret.License);

                    if (RenewLicense != null)
                        RenewLicense(this, new FirstStartEventArgs() { GuidApplication = Guid, GuidUser = UserGuid, License = ret.License });

                }
                return true;
            }
            return true;

        }

        private string GetUserId()
        {

            return string.Empty;

            //object i = RegistryHelper.Read(Registry.CurrentUser, SubKey, "UserId");

            //if (i == null)
            //    return null;

            //return i.ToString();

        }

        
        private string CreateUserId()
        {

            Guid g = Guid.NewGuid();

            if (Client == null)
                Client = new LicenceClient();

            ApplicationRegisterModelBack ret = Client.Register(new ApplicationRegisterModel() { GuidApplication = Guid.ToString(), GuidUser = g.ToString(), UserName = Environment.UserDomainName + @"\\" + Environment.UserName });

            if (ret.Result)
            {

                //RegistryHelper.Write(Registry.CurrentUser, SubKey, "ApplicationId", Guid);
                //RegistryHelper.Write(Registry.CurrentUser, SubKey, "UserId", g);
                //RegistryHelper.Write(Registry.CurrentUser, SubKey, "License", ret.License);

                if (FirstStart != null)
                    FirstStart(this, new FirstStartEventArgs() { GuidApplication = Guid, GuidUser = g, License = ret.License });

                return g.ToString();

            }

            return string.Empty;

        }

        private static DateTime GetDateEnd(string key)
        {

            try
            {

                // private static string template = "vvvvv-xddxmm-xyyxx-ppppp-ccccx";
                string[] tb = key.Split('-');
                int dd = int.Parse(tb[1].Substring(1, 2));
                int mm = int.Parse(tb[1].Substring(4, 2));
                int yy = int.Parse("20" + tb[2].Substring(1, 2));
                DateTime dte = new DateTime(yy, mm, dd);

                return dte;

            }
            catch (Exception)
            {
                return DateTime.Now.AddHours(-1);
            }
        
            
        }

        public static IApplicationOperationContract Client { get; set; }
        public static event EventHandler<FirstStartEventArgs> FirstStart;
        public static event EventHandler<FirstStartEventArgs> RenewLicense;


        #endregion

    }

}


